package com.castle.fortress.admin.study.exam.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.study.exam.dto.StudyQuestionDto;
import com.castle.fortress.admin.study.exam.entity.StudyQuestionEntity;
import com.castle.fortress.admin.study.exam.mapper.StudyQuestionMapper;
import com.castle.fortress.admin.study.exam.service.StudyQuestionService;
import com.castle.fortress.admin.utils.BizCommonUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import org.apache.poi.EmptyFileException;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 题目 服务实现类
 *
 * @author castle
 * @since 2023-02-10
 */
@Service
public class StudyQuestionServiceImpl extends ServiceImpl<StudyQuestionMapper, StudyQuestionEntity> implements StudyQuestionService {
    /**
    * 获取查询条件
    * @param studyQuestionDto
    * @return
    */
    public QueryWrapper<StudyQuestionEntity> getWrapper(StudyQuestionDto studyQuestionDto){
        QueryWrapper<StudyQuestionEntity> wrapper= new QueryWrapper();
        wrapper.orderByAsc("sort");
        if(studyQuestionDto != null){
            StudyQuestionEntity studyQuestionEntity = ConvertUtil.transformObj(studyQuestionDto,StudyQuestionEntity.class);
            wrapper.eq(studyQuestionEntity.getId() != null,"id",studyQuestionEntity.getId());
            wrapper.eq(studyQuestionEntity.getQbId() != null,"qb_id",studyQuestionEntity.getQbId());
            wrapper.eq(StrUtil.isNotEmpty(studyQuestionEntity.getQuestionType()),"question_type",studyQuestionEntity.getQuestionType());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getTitle()),"title",studyQuestionEntity.getTitle());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getTitleImg()),"title_img",studyQuestionEntity.getTitleImg());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getTitleMp3()),"title_mp3",studyQuestionEntity.getTitleMp3());
            wrapper.eq(StrUtil.isNotEmpty(studyQuestionEntity.getOptionType()),"option_type",studyQuestionEntity.getOptionType());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnalysis()),"analysis",studyQuestionEntity.getAnalysis());
            wrapper.eq(StrUtil.isNotEmpty(studyQuestionEntity.getAnswer()),"answer",studyQuestionEntity.getAnswer());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnswerA()),"answer_a",studyQuestionEntity.getAnswerA());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnswerB()),"answer_b",studyQuestionEntity.getAnswerB());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnswerC()),"answer_c",studyQuestionEntity.getAnswerC());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnswerD()),"answer_d",studyQuestionEntity.getAnswerD());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnswerE()),"answer_e",studyQuestionEntity.getAnswerE());
            wrapper.like(StrUtil.isNotEmpty(studyQuestionEntity.getAnswerF()),"answer_f",studyQuestionEntity.getAnswerF());
            wrapper.like(studyQuestionEntity.getStatus() != null,"status",studyQuestionEntity.getStatus());
            wrapper.like(studyQuestionEntity.getCreateUser() != null,"create_user",studyQuestionEntity.getCreateUser());
            wrapper.like(studyQuestionEntity.getCreateTime() != null,"create_time",studyQuestionEntity.getCreateTime());
            wrapper.like(studyQuestionEntity.getUpdateUser() != null,"update_user",studyQuestionEntity.getUpdateUser());
            wrapper.like(studyQuestionEntity.getUpdateTime() != null,"update_time",studyQuestionEntity.getUpdateTime());
            wrapper.like(studyQuestionEntity.getIsDeleted() != null,"is_deleted",studyQuestionEntity.getIsDeleted());
            wrapper.like(studyQuestionEntity.getSort() != null,"sort",studyQuestionEntity.getSort());
        }
        wrapper.orderByDesc("create_time");
        return wrapper;
    }


    @Override
    public IPage<StudyQuestionDto> pageStudyQuestion(Page<StudyQuestionDto> page, StudyQuestionDto studyQuestionDto) {
        QueryWrapper<StudyQuestionEntity> wrapper = getWrapper(studyQuestionDto);
        Page<StudyQuestionEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<StudyQuestionEntity> studyQuestionPage=baseMapper.selectPage(pageEntity,wrapper);
        Page<StudyQuestionDto> pageDto = new Page(studyQuestionPage.getCurrent(), studyQuestionPage.getSize(),studyQuestionPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(studyQuestionPage.getRecords(),StudyQuestionDto.class));
        return pageDto;
    }

    @Override
    public IPage<StudyQuestionDto> pageStudyQuestionExtends(Page<StudyQuestionDto> page, StudyQuestionDto studyQuestionDto){
        Map<String,Long> pageMap = BizCommonUtil.getPageParam(page);
        StudyQuestionEntity studyQuestionEntity = ConvertUtil.transformObj(studyQuestionDto,StudyQuestionEntity.class);
        List<StudyQuestionEntity> studyQuestionList=baseMapper.extendsList(pageMap,studyQuestionEntity);
        Long total = baseMapper.extendsCount(studyQuestionEntity);
        Page<StudyQuestionDto> pageDto = new Page(page.getCurrent(), page.getSize(),total);
        pageDto.setRecords(ConvertUtil.transformObjList(studyQuestionList,StudyQuestionDto.class));
        return pageDto;
    }
    @Override
    public StudyQuestionDto getByIdExtends(Long id){
        StudyQuestionEntity  studyQuestionEntity = baseMapper.getByIdExtends(id);
        return ConvertUtil.transformObj(studyQuestionEntity,StudyQuestionDto.class);
    }

    @Override
    public List<StudyQuestionDto> listStudyQuestion(StudyQuestionDto studyQuestionDto){
        QueryWrapper<StudyQuestionEntity> wrapper = getWrapper(studyQuestionDto);
        List<StudyQuestionEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,StudyQuestionDto.class);
    }

    @Override
    public boolean updateStudyQuestionSort(Long id, Integer sort) {
        return baseMapper.updateStudyQuestionSort(id,sort)>1;
    }

    @Override
    public boolean checkName(StudyQuestionEntity studyQuestionEntity) {
        QueryWrapper<StudyQuestionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("title",studyQuestionEntity.getTitle());
        wrapper.eq("qb_id",studyQuestionEntity.getQbId());
        wrapper.ne(studyQuestionEntity.getId()!=null,"id",studyQuestionEntity.getId());
        List<StudyQuestionEntity> list = baseMapper.selectList(wrapper);
        return (list!=null&&list.size()>0)?true:false;
    }

    @Override
    public RespBody<String> importQuestions(String fileUrl, Long qbId) {
        //对本地文件命名
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //服务器下载
            urlfile = new URL(fileUrl);
            // 本地下载
//            urlfile = new URL("file:///" + fileUrl);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 读取excel文件内容
        ExcelReader reader = null;
        try {
            reader = ExcelUtil.getReader(file);
            // 获取全部的内容
            List<Map> readAll = reader.read(1, 2, Map.class);
            // 新建新增内容的list
            List<StudyQuestionEntity> list = new ArrayList<>();
            for (Map<String, Object> map : readAll) {
                StudyQuestionEntity entity = new StudyQuestionEntity();
                entity.setQbId(qbId);
                entity.setOptionType("文字");
                String title = CommonUtil.emptyIfNull(map.get("题目名称"));
                if (StrUtil.isNotEmpty(title)) {
                    entity.setTitle(title);
                } else {
                    continue;
                }
                String questionType = CommonUtil.emptyIfNull(map.get("类型"));
                if (StrUtil.isNotEmpty(questionType)
                        && ("单选题".equals(questionType) || "多选题".equals(questionType))) {
                    entity.setQuestionType(questionType);
                } else {
                    continue;
                }
                String answer = CommonUtil.emptyIfNull(map.get("答案"));
                if (StrUtil.isNotEmpty(answer)) {
                    entity.setAnswer(answer);
                } else {
                    continue;
                }
                String analysis = CommonUtil.emptyIfNull(map.get("答案解析"));
                if (StrUtil.isNotEmpty(analysis)) {
                    entity.setAnalysis(analysis);
                }
                String answerA = CommonUtil.emptyIfNull(map.get("选项A"));
                if (StrUtil.isNotEmpty(answerA)) {
                    entity.setAnswerA(answerA);
                } else {
                    continue;
                }
                String answerB = CommonUtil.emptyIfNull(map.get("选项B"));
                if (StrUtil.isNotEmpty(answerB)) {
                    entity.setAnswerB(answerB);
                } else {
                    continue;
                }
                String answerC = CommonUtil.emptyIfNull(map.get("选项C"));
                if (StrUtil.isNotEmpty(answerC)) {
                    entity.setAnswerC(answerC);
                }
                String answerD = CommonUtil.emptyIfNull(map.get("选项D"));
                if (StrUtil.isNotEmpty(answerD)) {
                    entity.setAnswerD(answerD);
                }
                String answerE = CommonUtil.emptyIfNull(map.get("选项E"));
                if (StrUtil.isNotEmpty(answerE)) {
                    entity.setAnswerE(answerE);
                }
                String answerF = CommonUtil.emptyIfNull(map.get("选项F"));
                if (StrUtil.isNotEmpty(answerF)) {
                    entity.setAnswerF(answerF);
                }
                list.add(entity);
            }
            Integer batchSize = 100;
            if(list.size()<=batchSize){
                saveBatch(list);
            }else{
                int times = list.size()/batchSize;
                if(list.size()%batchSize != 0){
                    times+=1;
                }
                for(int i=0;i<times;i++){
                    List<StudyQuestionEntity> subList=list.subList(i*batchSize,(i+1)*batchSize>list.size()?list.size():(i+1)*batchSize);
                    saveBatch(subList);
                }
            }
        } catch (EmptyFileException e) {
            throw new BizException(BizErrorCode.TEMPLATE_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBody.data("导入成功");
    }
}

